package com.longnuoqi.mydoctor.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.longnuoqi.mydoctor.entity.Ask;
import com.longnuoqi.mydoctor.entity.Disease;
import com.longnuoqi.mydoctor.entity.Favorite;
import com.longnuoqi.mydoctor.entity.Hospital;
import com.longnuoqi.mydoctor.entity.News;
import com.longnuoqi.mydoctor.entity.Store;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import java.util.List;


/**
 * Created by Lenovo on 2015/12/29.
 */
public class FileUtil {

    public static String dateFormat(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(time);
        return sdf.format(date);
    }

    public static boolean fileIsExist(String name) {
        File path = Environment.getExternalStorageDirectory();
        File file = new File(path, name);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static byte[] Bitmap2Bytes(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);//png类型
        return baos.toByteArray();
    }

    public static void saveByte2File(byte[] bs, String name) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdCard = Environment.getExternalStorageDirectory();
            File file = new File(sdCard, name);
            try {
                OutputStream op = new FileOutputStream(file);
                op.write(bs);
                op.flush();
                op.close();
                Log.e("================", "save img:" + name + " success");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("================", "no sdcard!!!");
        }
    }

    public static Bitmap readByte4File(String name, Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdCard = Environment.getExternalStorageDirectory();
            File file = new File(sdCard, name);
            try {
                return BitmapFactory.decodeStream(new FileInputStream(file));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void saveFile(String value, String name) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdCard = Environment.getExternalStorageDirectory();
            File file = new File(sdCard, name);
            try {
                OutputStream op = new FileOutputStream(file);
                op.write(value.getBytes());
                op.flush();
                op.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String readFile(String name) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File sdDir = Environment.getExternalStorageDirectory();
            File file = new File(sdDir, name);
            try {
                InputStream in = new FileInputStream(file);
//                byte[] b = new byte[1024];
//                int len = -1;
//                StringBuffer buffer = new StringBuffer();
//                while ((len = in.read(b)) != -1) {
//                    buffer.append(new String(b, 0, len));
//                }
                InputStreamReader reader = new InputStreamReader(in);
                char[] c = new char[20];
                int len = -1;
                StringBuffer buffer = new StringBuffer();
                while ((len = reader.read(c)) != -1) {
                    buffer.append(c, 0, len);
                }
                return buffer.toString();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static List<News> json4NewsChannel(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            News news = null;
            List<News> list = new ArrayList<>();
            for (int i = 0; i < data.length(); i++) {
                news = new News();
                JSONObject info = data.getJSONObject(i);
                news.setId(Integer.parseInt(info.getString("id")));
                news.setTitle(info.getString("title"));
                list.add(news);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<News> json4NewsItem(String json) {
        try {
            News news = null;
            List<News> list = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            for (int i = 0; i < data.length(); i++) {
                news = new News();
                JSONObject info = data.getJSONObject(i);
                String description = info.getString("description");

                news.setId(Integer.parseInt(info.getString("id")));
                news.setTitle(info.getString("title"));
                news.setDescription("\t" + description.substring(0, description.length() / 2));
                news.setImg("http://tnfs.tngou.net/image" + info.getString("img") + "_120x100");
                list.add(news);
                Log.e("==================", "item:" + i + ":title:" + info.getString("title"));
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static News json4News(String json) {
        News news = null;
        try {
            news = new News();
            JSONObject data = new JSONObject(json);
            Log.e("===================", data.getString("title"));
            news.setId(Integer.parseInt(data.getString("id")));
            news.setTitle(data.getString("title"));

            long time = Long.parseLong(data.getString("time"));
            news.setTime(dateFormat(time));

            String str = StringRegex.parserString(data.getString("message"));
            String message = StringRegex.getString(str);
            if (message.trim().isEmpty()) {
                Log.e("==================", "news message str:" + str);
                news.setMessage("\t" + str);
            } else {
                Log.e("==================", "news message:" + message);
                news.setMessage("\t" + message);
            }
            news.setKeywords(data.getString("keywords"));
            return news;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return news;
    }

    public static List<Disease> jsonDepartment(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            List<Disease> list = new ArrayList<>();
            Disease disease = null;
            for (int i = 0; i < data.length(); i++) {
                disease = new Disease();
                JSONObject info = data.getJSONObject(i);
                disease.setId(info.getInt("id"));
                disease.setName(info.getString("name"));
                list.add(disease);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Disease> jsonDepartmentList(String json, int position) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("tngou");
            JSONObject object = jsonArray.getJSONObject(position);
            JSONArray data = object.getJSONArray("departments");
            Disease disease = null;
            List<Disease> list = new ArrayList<>();
            for (int i = 0; i < data.length(); i++) {
                disease = new Disease();
                JSONObject info = data.getJSONObject(i);
                disease.setId(info.getInt("id"));
                disease.setName(info.getString("name"));
                list.add(disease);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Disease> jsonDiseaseList(String json) {
        try {
            Disease disease = null;
            List<Disease> list = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("list");
            for (int i = 0; i < data.length(); i++) {
                disease = new Disease();
                JSONObject info = data.getJSONObject(i);
                disease.setId(info.getInt("id"));
                disease.setName(info.getString("name"));
                list.add(disease);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Disease jsonDisease(String json) {
        try {
            Disease disease = null;
            List<Disease> list = new ArrayList<>();
            JSONObject info = new JSONObject(json);
            disease = new Disease();

            String mess = StringRegex.parserString(info.getString("message")).replaceAll("\\s*", "");
            String message = StringRegex.getString(mess).trim();
            String cause = StringRegex.parserString(info.getString("causetext")).replaceAll("\\s*", "");
            String causetext = StringRegex.getString(cause).trim();
            String care = StringRegex.parserString(info.getString("caretext")).replaceAll("\\s*", "");
            String caretext = StringRegex.getString(care).trim();

            disease.setId(info.getInt("id"));
            disease.setName(info.getString("name"));
            disease.setImg(info.getString("img"));
            disease.setDepartment(info.getString("department"));
            disease.setPlace(info.getString("place"));
            if (!TextUtils.isEmpty(message)) {
                disease.setMessage(message);
            } else {
                disease.setMessage(mess);
            }
            disease.setKeywords(info.getString("keywords"));
            disease.setDescription(info.getString("description"));
            disease.setSymptom(info.getString("symptom"));
            disease.setDrug(info.getString("drug"));
            disease.setFood(info.getString("food"));
            disease.setDisease(info.getString("disease"));
            if (!TextUtils.isEmpty(causetext)) {
                disease.setMessage(causetext);
            } else {
                disease.setMessage(cause);
            }
            disease.setCausetext(causetext);
            disease.setChecks(info.getString("checks"));
            disease.setDisease(info.getString("disease"));
            disease.setCaretext(caretext);
            return disease;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Ask> jsonAskTypeList(String json) {
        try {
            Ask ask = null;
            List<Ask> list = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            for (int i = 0; i < data.length(); i++) {
                ask = new Ask();
                JSONObject info = data.getJSONObject(i);
                ask.setTitle(info.getString("title"));
                ask.setId(Integer.parseInt(info.getString("id")));
                list.add(ask);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Ask> jsonAskList(String json) {
        try {
            Ask ask = null;
            List<Ask> list = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            for (int i = 0; i < data.length(); i++) {
                ask = new Ask();
                JSONObject info = data.getJSONObject(i);
                ask.setTitle(info.getString("title"));
                long time = Long.parseLong(info.getString("time"));
                ask.setTime(dateFormat(time));
                ask.setId(Integer.parseInt(info.getString("id")));
                list.add(ask);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Ask jsonAsk(String json) {
        Ask ask = null;
        try {
            ask = new Ask();
            JSONObject data = new JSONObject(json);
            Log.e("===================", data.getString("title"));
            ask.setId(Integer.parseInt(data.getString("id")));
            ask.setTitle(data.getString("title"));
            long time = Long.parseLong(data.getString("time"));
            ask.setTime(dateFormat(time));

            String str = StringRegex.parserString(data.getString("message")).trim();
            String message = StringRegex.getString(str).trim();
            if (!TextUtils.isEmpty(message.trim())) {
                ask.setMessage(message);
            } else {
                if (!TextUtils.isEmpty(str.trim())) {
                    ask.setMessage(str);
                } else {
                    ask.setMessage(data.getString("message"));
                }
            }
            ask.setKeywords(data.getString("keywords"));
            return ask;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ask;
    }

    public static String httpGetRequest(String address) throws IOException {
        String line = "";
        URL url = new URL(address);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(5000);
        if (conn.getResponseCode() == 200) {
            InputStreamReader reader = new InputStreamReader(conn.getInputStream());
            BufferedReader buf = new BufferedReader(reader);
            StringBuilder builder = new StringBuilder();
            while ((line = buf.readLine()) != null) {
                builder.append(line);
            }
            buf.close();
            reader.close();
            conn.disconnect();
            line = builder.toString();
        } else {
            line = "页面加载失败！";
        }
        Log.e("+++++++++++++++++++", "httpRequest");
        return line;
    }

    public static List<Store> jsonStoreList(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            List<Store> list = new ArrayList<>();
            Store store = null;
            for (int i = 0; i < data.length(); i++) {
                store = new Store();
                JSONObject info = data.getJSONObject(i);
                store.setId(Integer.parseInt(info.getString("id")));
                store.setAddress(info.getString("address"));
                store.setBusiness(info.getString("business"));
                store.setImg("http://tnfs.tngou.net/image" + info.getString("img") + "_120x100");
                store.setName(info.getString("name"));
                store.setX(info.getDouble("x"));
                store.setY(info.getDouble("y"));
                list.add(store);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<Hospital> jsonHospitalList(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            List<Hospital> list = new ArrayList<>();
            Hospital hospital = null;
            for (int i = 0; i < data.length(); i++) {
                hospital = new Hospital();
                JSONObject info = data.getJSONObject(i);
                hospital.setId(Integer.parseInt(info.getString("id")));
                hospital.setAddress(info.getString("address"));
                hospital.setTel(info.getString("tel"));
                hospital.setImg("http://tnfs.tngou.net/image" + info.getString("img") + "_120x100");
                hospital.setName(info.getString("name"));
                hospital.setX(info.getDouble("x"));
                hospital.setY(info.getDouble("y"));
                list.add(hospital);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Hospital jsonHospital(String json) {
        try {
            JSONObject data = new JSONObject(json);
            Hospital hospital = null;
            hospital = new Hospital();
            hospital.setId(Integer.parseInt(data.getString("id")));
            hospital.setAddress(data.getString("address"));
            hospital.setLevel(data.getString("level"));
            String result = StringRegex.parserString(data.getString("message"));
            String message = StringRegex.getString(result);
            if (!TextUtils.isEmpty(message)) {
                hospital.setMessage(message);
            } else {
                if (!TextUtils.isEmpty(result)) {
                    hospital.setMessage(result);
                } else {
                    hospital.setMessage(data.getString("message"));
                }
            }
            hospital.setImg("http://tnfs.tngou.net/image" + data.getString("img") + "_120x100");
            hospital.setName(data.getString("name"));
            hospital.setX(data.getDouble("x"));
            hospital.setY(data.getDouble("y"));
            return hospital;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ArrayList<Favorite> jsonUserFavorite(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray data = jsonObject.getJSONArray("tngou");
            ArrayList<Favorite> list = new ArrayList<>();
            Favorite favorite = null;
            for (int i = 0; i < data.length(); i++) {
                JSONObject info = data.getJSONObject(i);
                favorite = new Favorite();
                favorite.setId(info.getInt("oid"));
                favorite.setType(info.getString("otype"));
                favorite.setTime(info.getLong("time") + "");
                favorite.setTitle(info.getString("title"));
                favorite.setUrl(info.getString("url"));
                list.add(favorite);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

}
